package com.totoro.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.totoro.domain.Staff;
import com.totoro.service.StaffService;
import com.totoro.util.CommonConstant;
import com.totoro.util.Page;

@Controller
@RequestMapping("/staff")
public class StaffController {

	@Autowired
	private StaffService staffService;

	@RequestMapping("/list")
	public ModelAndView list(Integer pageNo) {
		System.out.println("/staff/list");
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/staff/list");						  
		
		pageNo = pageNo == null ? 1 : pageNo;
		Page<Staff> pagedPost = staffService.getPagePosts(pageNo,
				CommonConstant.PAGE_SIZE);
		
		mav.addObject("pagedPost", pagedPost);
		mav.addObject("staffList", pagedPost.getResult());
		mav.addObject("pageNo", pageNo);
		return mav;
	}

	@RequestMapping("/findByName")
	public ModelAndView findByName(String name) {
		System.out.println("description: " + name);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/staff/list");
		mav.addObject("staffList",
				staffService.list("name", new String(name)));
		return mav;
	}

	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.GET)
	public String toSave(ModelMap modelMap) {	
		modelMap.addAttribute("staff",new Staff());
		return "/staff/saveOrUpdate";
	}
//	保存或更新
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	public String saveOrUpdate(@ModelAttribute("staff") Staff staff) {
		System.out.println("staff: " + staff);
//		如果id为null，则为save，否则update
		staffService.saveOrUpdate(staff);
		return "redirect:/staff/list.html";
	}

	@RequestMapping("/findById/{id}")
	public String findById(@PathVariable("id") Integer id, ModelMap modelMap) {
		modelMap.addAttribute("staff", staffService.get(id));
		return "/staff/saveOrUpdate";
	}

//	@RequestMapping("/update")
//	public String update(@ModelAttribute("staff") Staff staff) {
//		System.out.println(staff);
//		staffService.update(staff);
//		return "redirect:/staff/list.html";
//	}

	@RequestMapping("/delete/{id}")
	public String delete(Staff staff) {
		staffService.deleteObject(staff);
		return "redirect:/staff/list.html";
	}
	
	//增加评语模板json视图
	@RequestMapping("/findById")
	public String findByIdToJson(Integer id,ModelMap model){
		System.out.println("id的值为：" + id);
		Staff staff = staffService.get(id);
		System.out.println("describtion = " + staff.getName());
		model.addAttribute("describtion", staff.getName());
		return "staffJson";
	}

}
